<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleExport">导出</a-button>
        <a-button type="primary" @click="handleCreate">新增商家</a-button>
        <Popconfirm title="确定要删除吗" ok-text="确认" cancel-text="取消" @confirm="handleDelet">
          <a-button type="primary">批量删除</a-button>
        </Popconfirm>
      </template>
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormSchema,
    EditRecordRow,
    ActionItem,
    TableAction,
  } from '/@/components/Table';
  import { ListApi, DeleteApi, EditStateApi, ExportApi } from '/@/api/merchant/index';
  import { merchantTypes, onlineStatus } from '/@/assets/dic';
  import formatDic from '/@/utils/formatDic';
  import { Popconfirm } from 'ant-design-vue';
  import { downloadFile } from '/@/utils/file/download';
  // import { UserItem } from '/@/api/user/userModel';
  import { GetcitylistApi } from '/@/api/activityAdmin/index';
  export interface AreaList {
    city: string;
    cityEn: string;
    id: string;
  }
  const columns: BasicColumn[] = [
    {
      title: '店铺名称',
      dataIndex: 'shopName',
    },
    {
      title: '商家分类',
      dataIndex: 'type',
      format: formatDic(merchantTypes),
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '详细地址',
      dataIndex: 'address',
    },
    {
      title: '区域',
      dataIndex: 'bigareaForm',
    },
    {
      title: '入驻时间',
      dataIndex: 'createTime',
    },
    {
      title: '状态',
      dataIndex: 'isUse',
      format: formatDic(onlineStatus),
    },
  ];
  const colProps = {
    span: 6,
  };
  const schemas: FormSchema[] = [
    {
      label: '店铺名称',
      field: 'shopName',
      component: 'Input',
      colProps,
    },
    {
      label: '商家分类',
      field: 'type',
      component: 'Select',
      componentProps: {
        options: merchantTypes,
      },
      colProps,
    },
    {
      label: '状态',
      field: 'isUse',
      component: 'Select',
      componentProps: {
        options: onlineStatus,
      },
      colProps,
    },
    {
      label: '区域：',
      field: 'city',
      component: 'AreaCascader',
      colProps,
    },
    {
      field: 'createTime',
      label: '时间：',
      component: 'RangePicker',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
      colProps,
    },
  ];
  export default defineComponent({
    name: 'Merchant',
    components: {
      BasicTable,
      TableAction,
      Popconfirm,
    },
    setup() {
      const router = useRouter();
      let formStatus = reactive({});
      const citylist = ref<AreaList[]>([]);
      const [registerTable, { reload, getSelectRows }] = useTable({
        api: ListApi,
        rowSelection: {
          type: 'checkbox',
        },
        useSearchForm: true,
        // showIndexColumn:true,
        columns,
        formConfig: {
          schemas,
          labelWidth: 100,
        },
        beforeFetch(params) {
          if (Array.isArray(params.city)) {
            params.area = params.city[1];
            params.city = params.city[0];
          }
          if (Array.isArray(params.createTime)) {
            params.createTime = params.createTime.join('~');
          }
        },
        handleSearchInfoFn(params) {
          if (Array.isArray(params.city)) {
            params.area = params.city[1];
            params.city = params.city[0];
          }
          if (Array.isArray(params.createTime)) {
            params.createTime = params.createTime.join('~');
          }
          formStatus = params;
        },
        afterFetch(record) {
          record.forEach((element) => {
            const cityItem = citylist.value.filter((item) => {
              return item.id == element.city;
            });
            if (cityItem.length > 0) {
              element.bigareaForm = `${cityItem[0].city || ''}-${element.area || ''}`;
            }
          });
        },
        actionColumn: {
          width: 180,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      function Getcitylist() {
        GetcitylistApi().then((res) => {
          if (res.code == 200) {
            citylist.value = res.data;
          }
        });
      }
      Getcitylist();
      // 新增商家
      function handleCreate() {
        router.push({
          path: '/merchantInfo',
        });
      }
      // 表格按钮
      function createActions(record: EditRecordRow, _: BasicColumn): ActionItem[] {
        return [
          {
            label: '编辑',
            color: 'success',
            onClick() {
              handleEdit(record.id);
            },
          },
          {
            label: record.isUse === 0 ? '上线' : '下线',
            onClick: handleChangeStatus.bind(null, record as EditState),
          },
          {
            label: '删除',
            color: 'error',
            popConfirm: {
              title: '确定要删除吗！',
              confirm() {
                handleDelet();
              },
            },
          },
        ];
      }
      // 编辑
      function handleEdit(id: number) {
        router.push({
          path: '/merchantInfo',
          query: {
            id,
          },
        });
      }
      // 删除
      function handleDelet() {
        const selectRows = getSelectRows();
        const ids = selectRows.map((item) => item.id);
        const _ids = ids.join(',');
        DeleteApi(_ids).then((_) => {
          reload();
        });
      }
      // 改变状态
      function handleChangeStatus(record: EditState) {
        record.isUse = record.isUse === 0 ? 1 : 0;
        EditStateApi(record).then((_) => {
          reload();
        });
      }
      // 导出
      async function handleExport() {
        // return console.log(formStatus);
        const res = await ExportApi(formStatus);
        downloadFile(res.msg);
      }
      return {
        registerTable,
        handleCreate,
        handleDelet,
        createActions,
        handleExport,
      };
    },
  });
</script>
<style lang="less" scoped></style>
